package com.hui.dbmigrator.service;

import com.hui.dbmigrator.dto.request.MigrationRequest;
import com.hui.dbmigrator.entity.TableDefinition;
import com.hui.dbmigrator.handler.DatabaseHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

// MigrationService.java
@Service
@RequiredArgsConstructor
public class MigrationService {

    private final DatabaseService databaseService;
    private final TypeConversionService typeConversionService;

    public String migrateTable(MigrationRequest request) throws SQLException {
        // 1. 获取处理器
        DatabaseHandler sourceHandler = databaseService.getHandler(request.getSource().getType().getDisplayName());
        DatabaseHandler targetHandler = databaseService.getHandler(request.getTarget().getType().getDisplayName());

        // 2. 提取源表结构
        TableDefinition sourceTable = sourceHandler.extractTable(
                request.getTableName(),
                request.getSource());

        // 3. 转换表结构
        TableDefinition targetTable = convertTable(
                sourceTable,
                request.getSource().getType().getDisplayName(),
                request.getTarget().getType().getDisplayName());

        // 4. 生成并执行DDL
        String ddl = targetHandler.generateCreateTable(targetTable);
        targetHandler.execute(request.getTarget(), ddl);

        return ddl;
    }

    public TableDefinition convertTable(TableDefinition source, String sourceDb, String targetDb) {
        TableDefinition target = new TableDefinition();
        target.setName(source.getName());
        target.setComment(source.getComment());

        // 转换每个列
        for (TableDefinition.ColumnDefinition srcCol : source.getColumns()) {
            TableDefinition.ColumnDefinition dstCol = new TableDefinition.ColumnDefinition();
            dstCol.setName(srcCol.getName());

            // 转换类型
            String targetType = typeConversionService.convertType(
                    srcCol.getType(), sourceDb, targetDb);

            dstCol.setType(targetType);
            dstCol.setNullable(srcCol.isNullable());
            dstCol.setDefaultValue(srcCol.getDefaultValue());
            dstCol.setComment(srcCol.getComment());
            dstCol.setPrimaryKey(srcCol.isPrimaryKey());

            target.getColumns().add(dstCol);
        }

        return target;
    }
}